using System.Collections.Generic;
using System.Collections;
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Text;
using Cysharp.Threading.Tasks;

public partial class UICodeGenerator 
{
    public string GenteratorConfig(string className,bool isItem,string oldCode = "")
    {
        string code = "";
        if(isItem)
        {
            code = GenerateUIItemConfig(className,oldCode);
        }else
        {
            code = GenerateUIConfig(className,oldCode);
        }
        return code;
    }

    //UI配置生成
    string GenerateUIConfig(string className,string oldCode = "")
    {
        string content = RegexMgr.Instance.RegexBeginAndEnd(oldCode, "{", "}");
        // Debug.Log(content);
        StringReader sr = new StringReader(content.Trim());
        bool hasEnum = false;
        string line = "";
        while((line = sr.ReadLine()) != null)
        {
            if(line.Contains(className.ToUpper()+","))
            {
                hasEnum = true;
                break;
            }
        }
        sr.Close();
        StringBuilder s = new StringBuilder();
        s.AppendLine("public enum UINAMES");
        s.AppendLine("{");
        s.AppendLine("\t" + content.Trim());
        if(!hasEnum)
        {
            s.AppendLine("\t" + className.ToUpper() + ",");
        }
        s.AppendLine("}");
        var new_code = s.ToString();
        return new_code;
    }

    //UIItem配置生成
    string GenerateUIItemConfig(string className,string oldCode = "")
    {
        string content = RegexMgr.Instance.RegexBeginAndEnd(oldCode, "{", "}");
        // Debug.Log(content);
        StringReader sr = new StringReader(content.Trim());
        bool hasEnum = false;
        string line = "";
        while((line = sr.ReadLine()) != null)
        {
            if(line.Contains(className.ToUpper()+","))
            {
                hasEnum = true;
                break;
            }
        }
        sr.Close();
        StringBuilder sb = new StringBuilder();
        sb.AppendLine("public enum UIITEMS");
        sb.AppendLine("{");
        sb.AppendLine("\t" + content.Trim());
        if(!hasEnum)
        {
            sb.AppendLine("\t" + className.ToUpper() + ",");
        }
        sb.AppendLine("}");
        var new_code = sb.ToString();
        return new_code;
    }

    //UI asset 生成
    public void GeneratorUIAsset(GameObject prefab,string className)
    {
        var dir = EditorPathMgr.Instance.UIEditorCfgPath;
        if(!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
        }
        var file = dir + "/" + className + ".asset";
        // assetdatabase load asset
        var data = AssetDatabase.LoadAssetAtPath<UIEditorItem>(file);
        if(data == null)
        {
            data = ScriptableObject.CreateInstance<UIEditorItem>();
            data.Name = GetUIName(className);
            data.Prefab = prefab;
            AssetDatabase.CreateAsset(data, file);
            EditorUtility.SetDirty(data);
        }else{
            data.Name = GetUIName(className);
            data.Prefab = prefab;
            EditorUtility.SetDirty(data);
        }
        // AssetDatabase.SaveAssets();
    }

    public void GeneratorUIItemAsset(GameObject prefab,string className)
    {
        var dir = EditorPathMgr.Instance.UIItemEditorCfgPath;
        if(!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
        }
        var file = dir + "/" + className + ".asset";
        // assetdatabase load asset
        var data = AssetDatabase.LoadAssetAtPath<UITemplateEditorItem>(file);
        if(data == null)
        {
            data = ScriptableObject.CreateInstance<UITemplateEditorItem>();
            data.Name = GetUIItemName(className);
            data.Prefab = prefab;
            AssetDatabase.CreateAsset(data, file);
            EditorUtility.SetDirty(data);
        }else{
            data.Name = GetUIItemName(className);
            data.Prefab = prefab;
            EditorUtility.SetDirty(data);
        }
        // AssetDatabase.SaveAssets();
    }

    public async void ExportUIConfig()
    {
        // AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
        await UniTask.Delay(3000);
        var dir = EditorPathMgr.Instance.UIEditorCfgPath;
        var filePath = EditorPathMgr.Instance.GameUICfgAsset;
        var config = AssetDatabase.LoadAssetAtPath<UIConfig>(filePath);
        if (config == null)
        {
            config = ScriptableObject.CreateInstance<UIConfig>();
            AssetDatabase.CreateAsset(config, filePath);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }
        if (config.Dic == null)
        {
            config.Dic = new List<UIItemCfg>();
        }
        config.Dic.Clear();
        // search all asset
        var guids = AssetDatabase.FindAssets("t:UIEditorItem", new string[] { dir });
        foreach (var guid in guids)
        {
            var path = AssetDatabase.GUIDToAssetPath(guid);
            var data = AssetDatabase.LoadAssetAtPath<UIEditorItem>(path);
            if (data != null)
            {
                var item = new UIItemCfg();
                item.Name = data.Name;
                string prefab = AssetDatabase.GetAssetPath(data.Prefab);
                item.Prefab = prefab;
                item.Layer = data.Layer;
                item.FullScreen = data.FullScreen;
                config.Dic.Add(item);
            }
        }
    }

    public async void ExportUIItemConfig()
    {
        // AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
        await UniTask.Delay(3000);
        var dir = EditorPathMgr.Instance.UIItemEditorCfgPath;
        var filePath = EditorPathMgr.Instance.GameUICfgAsset;
        var config = AssetDatabase.LoadAssetAtPath<UIConfig>(filePath);
        if (config == null)
        {
            config = ScriptableObject.CreateInstance<UIConfig>();
            AssetDatabase.CreateAsset(config, filePath);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }
        if (config.ItemDic == null)
        {
            config.ItemDic = new List<UITemplate>();
        }
        config.ItemDic.Clear();
        // search all asset
        var guids = AssetDatabase.FindAssets("t:UITemplateEditorItem", new string[] { dir });
        foreach (var guid in guids)
        {
            var path = AssetDatabase.GUIDToAssetPath(guid);
            var data = AssetDatabase.LoadAssetAtPath<UITemplateEditorItem>(path);
            if (data != null)
            {
                var item = new UITemplate();
                item.Name = data.Name;
                string prefab = AssetDatabase.GetAssetPath(data.Prefab);
                item.Prefab = prefab;
                config.ItemDic.Add(item);
            }
        }
    }

    UINAMES GetUIName(string name)
    {
        var tmp = name.ToUpper();
        foreach(var item in System.Enum.GetValues(typeof(UINAMES)))
        {
            if(tmp == item.ToString())
            {
                return (UINAMES)item;
            }
        }
        return UINAMES.NONE;
    }

    UIITEMS GetUIItemName(string name)
    {
        var tmp = name.ToUpper();
        foreach(var item in System.Enum.GetValues(typeof(UIITEMS)))
        {
            if(tmp == item.ToString())
            {
                return (UIITEMS)item;
            }
        }
        return UIITEMS.NONE;
    }
}